<template>
  <div
    class="flex items-center justify-center min-h-screen bg-gradient-to-r from-blue-400 to-purple-500"
  >
    <n-card
      class="w-full max-w-md shadow-xl rounded-lg size-huge"
      role="dialog"
      aria-modal="true"
      aria-labelledby="login"
    >
      <h2 class="text-center">登录</h2>
      <n-form ref="formRef" :model="model" :rules="rules">
        <n-form-item
          label="用户名"
          path="username"
          :label-style="{ fontSize: '18px' }"
        >
          <n-input
            v-model:value="model.username"
            type="text"
            placeholder="请输入用户名"
          />
        </n-form-item>
        <n-form-item
          label="密码"
          path="password"
          size="large"
          :label-style="{ fontSize: '18px' }"
        >
          <n-input
            v-model:value="model.password"
            placeholder="请输入密码"
            type="password"
            show-password-on="mousedown"
          />
        </n-form-item>
        <n-form-item>
          <n-button
            type="primary"
            size="large"
            class="rounded-lg w-full"
            @click="handleLogin"
            >登录</n-button
          >
        </n-form-item>
      </n-form>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import {
  NCard,
  NForm,
  NFormItem,
  NInput,
  NButton,
  type FormRules,
} from "naive-ui";
import type { LoginModel } from "@/api/login/model";
import { loginApi } from "@/api/login";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";

const router = useRouter();
const formRef = ref();

const model = ref<LoginModel>({
  username: "admin@qq.com",
  password: "123456",
});

const rules: FormRules = {
  username: [{ required: true, message: "请输入用户名" }],
  password: [
    { required: true, message: "请输入密码" },
    { min: 6, max: 16, message: "密码长度为6到16位" },
  ],
};

const handleLogin = async () => {
  const valid = await formRef.value.validate();
  if (!valid) {
    return;
  }

  try {
    const res = await loginApi({
      username: model.value.username,
      password: model.value.password,
    });
    if (res.code === 200) {
      router.push(router.currentRoute.value.redirectedFrom?.path || "/");
    } else {
      message.error("账号或密码错误");
    }
  } catch (_) {
    message.error("登录失败");
  }
};
</script>

<style scoped>
.bg {
  background: url("../../assets/images/login/bg.png") no-repeat center center;
  background-size: cover;
  height: 100vh;
  width: 100vw;
}

.login-form {
  width: 472px;
  height: 446px;
  background: #ffffff;
  box-shadow: 0px 0px 30px 0px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  position: absolute;
  top: 50%;
  left: 75%;
  transform: translate(-50%, -50%);
}

h2 {
  font-size: 24px;
  font-weight: 600;
  color: #333333;
  text-align: center;
  margin-bottom: 24px;
}
</style>
